package org.niux.AutoLoginQQ.util;

/**
* 加密WEBqq 传输时的密码
* @author weirhp@gmail.com
*    http://weibo.com/weirhp
*/
public class EncodeQQPass {

    public static void main(String[] args) {
    	System.out.println("e9e62aeab905b5a17da037bccb2022a22557bdff12d63dc8".toUpperCase());
        System.out.println(encodePass("lsm071106", "1a22f3db7c633cefff571db0fc79e60e45fd4308a8d52581",
                "\\x00\\x00\\x00\\x00\\x00\\x49\\xde\\x46"));
    }

    public static String encodePass(String password, String vcode, String uin) {
        String[] us = uin.split("\\\\x");
        byte[] uinByte = new byte[us.length - 1];
        if (us.length == 9) {
            for (int i = 1; i < us.length; i++) {
                uinByte[i - 1] = getByte(Integer.parseInt(us[i], 16));
            }
        }
        return md5(md5(getByte(hexchar2bin(md5(password)), uinByte))
                + vcode.toUpperCase());
    }

    public static String md5(byte[] source) {
        String s = null;
        char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                'a', 'b', 'c', 'd', 'e', 'f' };
        try {
            java.security.MessageDigest md = java.security.MessageDigest
                    .getInstance("MD5");
            md.update(source);
            byte tmp[] = md.digest();
            char str[] = new char[16 * 2];
            int k = 0;
            for (int i = 0; i < 16; i++) {
                byte byte0 = tmp[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            s = new String(str);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return s.toUpperCase();
    }

    public static String md5(String str) {
        return md5(str.getBytes()).toUpperCase();
    }

    public static byte[] hexchar2bin(String str) {
        byte[] bytes = new byte[str.length() / 2];
        int j = 0;
        for (int i = 0; i < str.length(); i = i + 2) {
            int iv = Integer.parseInt(str.substring(i, i + 2), 16);
            bytes[j++] = getByte(iv);
        }
        return bytes;
    }

    public static byte getByte(int intValue) {
        int byteValue = 0;
        int temp = intValue % 256;
        if (intValue < 0) {
            byteValue = temp < -128 ? 256 + temp : temp;
        } else {
            byteValue = temp > 127 ? temp - 256 : temp;
        }
        return (byte) byteValue;
    }

    public static byte[] getByte(byte[] b1, byte[] b2) {
        byte[] bs = new byte[b1.length + b2.length];
        int i = 0;
        for (i = 0; i < b1.length; i++) {
            bs[i] = b1[i];
        }
        for (int j = 0; j < b2.length; j++) {
            bs[i + j] = b2[j];
        }
        return bs;
    }
}
